package xu.jiang.report.dealer.layer;

import net.sf.json.JSON;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.util.CellRangeAddress;
import xu.jiang.report.Param;
import xu.jiang.report.R;
import xu.jiang.report.bean.LayerOption;

import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * 单例
 * 层工厂
 */
public class LayerFactory {

    private LayerFactory(){

    }

    public static final LayerFactory instance = new LayerFactory();


    public  ILayerDealer create(LayerBaseParam layerBaseParam) throws IOException {
        /**
         * 针对 层的细分，请参考如下规则：
         * 检查 option 替换符？
         * 不存在则 为 LoopLayer
         * 存在，则解析值
         */
        int index = layerBaseParam.index;
        List<String> columns = layerBaseParam.columns;
        Set<CellRangeAddress> mergingColumns = layerBaseParam.mergingColumns;
        Param param = layerBaseParam.param;

        Optional<String> optional = columns.stream().filter(e->e.matches(R.Layer.LayerOption_REGEX)).findFirst();
        if(!optional.isPresent()){
            // 将该层的属性的值添加到Layers中
            return new LoopLayer(layerBaseParam);
        }
        String json4LayerOption = optional.get();
        if(StringUtils.isBlank(json4LayerOption)){
            return new LoopLayer(layerBaseParam);
        }
        //剔除前缀
        String jsonStr = json4LayerOption.substring(json4LayerOption.indexOf("{"));

        LayerOption layerOption = (LayerOption) JSONObject.toBean(JSONObject.fromObject(jsonStr),LayerOption.class);
        if(layerOption==null||layerOption.getDataHeightInHeadPage()==null){
            return new LoopLayer(layerBaseParam);
        }
        //是否为 PrintLayer
        if(layerOption.getStartRowIndexOfModel()!=null){
            return new PrintLayer(layerBaseParam,layerOption);
        }
        return new FixedDataHeightLayer(layerBaseParam,layerOption.getDataHeightInHeadPage());
    }



}
